package cn.liutao.order.api;

import cn.hutool.core.util.StrUtil;
import cn.liutao.common.exception.BadRequestException;
import cn.liutao.common.utils.ServletUtils;
import cn.liutao.order.entity.dto.AlipayStatusDto;
import cn.liutao.order.service.PayService;
import com.alipay.api.domain.AreaCode;
import com.alipay.api.internal.util.AlipaySignature;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

/**
 * @author: liutao
 * @description: 支付回调
 * @date: 2023/12/14 9:15
 */
@WebServlet("/order/payresult")
@Slf4j
public class PayResultServlet extends HttpServlet {
    private PayService payService;
    private static String alipayPublicKey;
    private static String appID;
    @Override
    public void init() throws ServletException {
        payService = PayService.getInstance();
        Properties properties = new Properties();
            InputStream is = AreaCode.class.getClassLoader().getResourceAsStream("alipay.properties");
        try {
            properties.load(is);
        } catch (IOException e) {
            log.error("读取配置文件出错");
        }
        alipayPublicKey= properties.getProperty("alipay_public_key");
        appID = properties.getProperty("app_id");
    }

    /**
     * 主动查询结果
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        log.debug("手动查询支付结果");
        String payNo = req.getParameter("payNo");
        if (StrUtil.isBlank(payNo)){
            throw new BadRequestException("支付记录不能为空");
        }
        AlipayStatusDto payResult = payService.getResult(payNo);
        if ("TRADE_SUCCESS".equals(payResult.getTradeStatus())){
            ServletUtils.ok(resp,"支付成功");
        }else {
            ServletUtils.error(resp,payResult.getTradeStatus());
        }
    }

    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取支付宝POST过来反馈信息
        log.debug("自动查询支付结果");
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
        //商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //支付宝交易号

        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

        //交易状态
        String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

        String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
        //计算得出通知验证结果
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean verify_result = AlipaySignature.rsaCheckV1(params,alipayPublicKey,"UTF-8", "RSA2");
        log.debug("自动查询支付结果:{}",trade_status);
        if(verify_result){//验证成功
            if (trade_status.equals("TRADE_SUCCESS")){
                //更新订单状态
                AlipayStatusDto statusDto = new AlipayStatusDto();
                statusDto.setTradeStatus(trade_status);
                statusDto.setTradeNo(trade_no);
                statusDto.setAppId(appID);
                statusDto.setTotalAmount(total_amount);
                statusDto.setOutTradeNo(out_trade_no);
                payService.saveAliPayStatus(statusDto);
            }
            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
//            out.clear();
//            out.println("success");	//请不要修改或删除
            response.getWriter().println("success");
            //////////////////////////////////////////////////////////////////////////////////////////
        }else{//验证失败
//            out.println("fail");
            response.getWriter().println("fail");
        }
    }
}
